<template>
  <XenPageLayout
    title="招聘中心详情"
    title-align="left"
    navbar-bg-color="#7881de"
    navbar-text-color="#ffffff"
    navbar-icon-color="#ffffff"
    contentStyle="background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); padding: 0; height: 100vh; display: flex; flex-direction: column;"
    :loading="loading"
    :error="hasError"
    @retry="loadRecruitPublishDetail(Id)"
  >
    <!-- 内容区域 -->
    <view class="details-container">
      <!-- 详情内容 -->
      <view class="details-card">
        <view class="card-content">
          <!-- 使用动态详情组件 -->
          <XenDynamicDetailsCard
            :sections="formSections"
            :data="originalData"
            :field-mapping="fieldMapping"
            :get-image-url="getImageUrl"
            @preview-image="previewImage"
          />

          <!-- 审核时间线组件 - 所有用户都有权限查看 -->
          <XenAuditTimeline :steps="timelineData" />
        </view>
      </view>
    </view>

    <!-- 固定底部应聘申请按钮 -->
    <view class="apply-button-container" v-if="originalData">
      <view class="apply-button" @click="handleJobApplication">
        <uni-icons type="personadd" size="20" color="#ffffff"></uni-icons>
        <text class="apply-button-text">应聘申请</text>
      </view>
    </view>
  </XenPageLayout>
</template>

<script setup lang="ts">
import { ref, onMounted } from "vue";
import { onLoad, onShareAppMessage } from "@dcloudio/uni-app";
import XenPageLayout from "@/layouts/XenPageLayout.vue";
import XenDynamicDetailsCard from "@/components/XenDynamicDetailsCard.vue";
import XenAuditTimeline from "@/components/XenAuditTimeline.vue";
import { getFormSectionsByPageType } from "./form-config";
import { useRecruitPublishInfo } from "./composables/useInfo";

import commonApi from "@/api/common";
import type { QueryTimeline, WorkflowInfo } from "@/type/common";

// 获取详情页面的表单分组配置
const formSections = getFormSectionsByPageType("details");

// 页面状态
const Id = ref<string>("");
const hasError = ref<boolean>(false);

// 审核相关数据
const timelineData = ref<WorkflowInfo[]>([]);

// 创建API实例
const commonApiInstance = commonApi();

// 使用招聘发布申请信息 Composable
const {
  loading,
  originalData,
  getImageUrl,
  initializeOptions,
  loadRecruitPublishDetail,
  fieldMapping,
} = useRecruitPublishInfo();

// 获取时间线数据
const getTimelineData = async () => {
  if (!Id.value) return;

  try {
    const params: QueryTimeline = {
      entityId: Id.value,
      entitytype: "HengTong.Model.Db.Bill.SysHrRecruitPublishRequestBill",
    };

    const response = await commonApiInstance.getTimeline(params);
    timelineData.value = response || [];
  } catch (error) {
    console.error("获取时间线数据失败:", error);
    timelineData.value = [];
  }
};

// 预览图片 - 统一的图片预览函数
const previewImage = (fileId: string | null) => {
  if (!fileId) {
    uni.showToast({
      title: "图片无效",
      icon: "none",
    });
    return;
  }

  const imageUrl = getImageUrl(fileId);
  if (!imageUrl) {
    uni.showToast({
      title: "图片无效",
      icon: "none",
    });
    return;
  }

  uni.previewImage({
    urls: [imageUrl],
    current: imageUrl,
    fail: () => {
      uni.showToast({
        title: "预览图片失败",
        icon: "none",
      });
    },
  });
};

// 获取分享标题
const getShareTitle = () => {
  if (originalData.value?.BillCode) {
    return `招聘中心${originalData.value.BillCode}`;
  }
  return "招聘中心详情";
};

// 获取分享路径
const getSharePath = () => {
  if (Id.value) {
    return `/subpkg-hr-syshrrecruitpublishrequestbill/details?id=${Id.value}`;
  }
  return "/subpkg-hr-syshrrecruitpublishrequestbill/index";
};

// 处理应聘申请
const handleJobApplication = () => {
  if (!originalData.value) {
    uni.showToast({
      title: "招聘信息加载中，请稍后",
      icon: "none",
      duration: 2000,
    });
    return;
  }

  const recruitId = originalData.value.ID || Id.value;
  if (!recruitId) {
    uni.showToast({
      title: "招聘信息ID缺失",
      icon: "none",
      duration: 2000,
    });
    return;
  }

  // 跳转到应聘申请新增页，并传递招聘发布单ID
  uni.navigateTo({
    url: `/subpkg-hr-syshrinterviewrequestbill/create?recruitPublishId=${recruitId}&recruitTitle=${encodeURIComponent(
      originalData.value.Title || "招聘信息",
    )}&company=${encodeURIComponent(
      originalData.value.OrgName || "",
    )}&department=${encodeURIComponent(originalData.value.GroupName || "")}`,
    fail: (error) => {
      console.error("跳转失败:", error);
      uni.showToast({
        title: "跳转失败，请稍后重试",
        icon: "none",
        duration: 2000,
      });
    },
  });
};

// 页面加载时获取路由参数
onLoad((options) => {
  if (options?.id) {
    Id.value = options.id;
  } else {
    uni.showToast({
      title: "缺少ID参数",
      icon: "none",
    });
  }

  // 设置微信小程序分享功能
  // #ifdef MP-WEIXIN
  onShareAppMessage(() => {
    return {
      title: getShareTitle(),
      path: getSharePath(),
      imageUrl: "", // 可以设置分享图片
    };
  });
  // #endif
});

// 页面挂载后加载数据
onMounted(async () => {
  // 先加载选项数据
  await initializeOptions();

  if (Id.value) {
    const result = await loadRecruitPublishDetail(Id.value);
    if (!result.success) {
      hasError.value = true;
    } else {
      // 加载成功后，获取时间线数据
      await getTimelineData();
    }
  }
});
</script>

<style lang="scss" scoped>
.details-container {
  flex: 1;
  padding: 10px;
  overflow-y: auto;
  min-height: calc(100vh - 80px);
  // 为固定底部按钮预留空间
  padding-bottom: calc(80px + constant(safe-area-inset-bottom));
  padding-bottom: calc(80px + env(safe-area-inset-bottom));

  .details-card {
    background: #ffffff;
    border-radius: 16px;
    box-shadow: 0 4px 16px rgba(0, 0, 0, 0.1);
    overflow: hidden;

    .card-header {
      padding: 20px 24px;
      border-bottom: 1px solid #f0f0f0;

      .form-title {
        font-size: 18px;
        font-weight: 600;
        color: #333;
        display: block;
        margin-bottom: 4px;
      }

      .form-subtitle {
        font-size: 14px;
        color: #666;
      }
    }

    .card-content {
      padding: 24px;
    }
  }
}

// 应聘申请按钮样式
.apply-button-container {
  position: fixed;
  left: 0;
  right: 0;
  bottom: 0;
  padding: 16px 24px;
  padding-bottom: calc(16px + constant(safe-area-inset-bottom));
  padding-bottom: calc(16px + env(safe-area-inset-bottom));
  background: rgba(255, 255, 255, 0.95);
  backdrop-filter: blur(10px);
  border-top: 1px solid rgba(0, 0, 0, 0.1);
  z-index: 1000;

  .apply-button {
    width: 100%;
    height: 48px;
    background: linear-gradient(135deg, #67c23a, #85ce61);
    border-radius: 24px;
    display: flex;
    align-items: center;
    justify-content: center;
    gap: 8px;
    box-shadow: 0 4px 12px rgba(103, 194, 58, 0.3);
    transition: all 0.3s ease;

    &:active {
      transform: scale(0.98);
      opacity: 0.8;
    }

    .apply-button-text {
      color: #ffffff;
      font-size: 16px;
      font-weight: 600;
    }
  }
}
</style>
